package com.vilynn.interview.huawei.nowcoder;

import java.util.ArrayList;
import java.util.List;

/**
 * 华为面试题2
 *
 * 字符串划分片段
 */
public class Interview2 {

    public static void main(String[] args) {
//        String s = "abcdefaacnmjlp";
        String s = "ababcbacadefegdehijhklij";
        int[] arrays = sp(s);
        for (int i = 0; i < arrays.length; i++) {
            System.out.println(arrays[i]);
        }
    }

    private static int[] sp(String s) {

        List<String> stringList = sub(s);

        int size = stringList.size();
        int[] arrays = new int[size];
        for (int i = 0; i < arrays.length; i++) {
            arrays[i] = stringList.get(i).length();
            System.out.println(stringList.get(i));
        }
        return arrays;
    }

    private static List<String> sub(String string) {
        List<String> stringList = new ArrayList<>();
        String temp = string;
        for (int i = 0; i < string.length();) {
            char c = string.charAt(i);
            int lastIndexOf = temp.lastIndexOf(c);
            if (lastIndexOf >= temp.length()-1) {
                stringList.add(temp);
                break;
            }
            i += lastIndexOf+1;
            String substring = temp.substring(0, lastIndexOf + 1);
            temp = string.substring(i);

            StringBuilder stringBuilder = new StringBuilder();
            for (int j = 0; j < substring.length(); j++) {
                char c2 = substring.charAt(j);
                int lastIndexOf2 = temp.lastIndexOf(c2);
                if (lastIndexOf2 == -1) {
                    continue;
                } else {
                    i += lastIndexOf2+1;
                    temp = temp.substring(lastIndexOf2+1);
                    stringBuilder.append(temp, 0, lastIndexOf2+1);
                }
            }
            stringList.add(substring + stringBuilder.toString());
        }
        return stringList;
    }

}
